package com.zyq.support.ui.task;

import com.zyq.support.FileOperation;
import javafx.concurrent.Task;

import java.io.File;

/**
 * Created by 邹宇泉 on 2017/11/20.
 */
public class MoveOrCopyOrDelte extends Task<Void> {
    private File[] files;
    private File target_dir;
    private String keywords;
    private Type type;

    public enum Type {
        move, copy, delete
    }

    public MoveOrCopyOrDelte(File[] files, File target_dir, Type type) {
        this.files = files;
        this.target_dir = target_dir;
        this.type = type;
        if (type == Type.copy) {
            this.keywords = "复制";
        } else if (type == Type.move) {
            this.keywords = "移动";
        } else {
            this.keywords = "删除";
        }

    }

    @Override
    protected Void call() throws Exception {
        if (callBack != null) callBack.before();
        if (files != null && files.length != 0) {
            updateMessage(String.format("准备%s：%d文件", keywords, files.length));
            FileOperation.FileMoveListener listener = (isSuccess, moved, count, file, isDir) -> {
                String info = String.format("%s%s%s  %s", keywords, file.getName(), isSuccess ? "成功" : "失败", moved + "/" + count);
                System.out.println(info);
                updateMessage(info);
                updateProgress(moved, count);
            };
            if (type == Type.copy) {
                FileOperation.copyDir(files, target_dir, listener);
            } else if (type == Type.move) {
                FileOperation.moveDir(files, target_dir, listener);
            } else {
                FileOperation.deleteDir(files, listener);
            }
            updateMessage(String.format("%s完成", keywords));
            updateProgress(100, 100);
        } else {
            updateMessage("源目录为空文件夹");
        }
        if (callBack != null) callBack.after();
        return null;
    }

    private CallBack callBack;

    public CallBack getCallBack() {
        return callBack;
    }

    public void setCallBack(CallBack callBack) {
        this.callBack = callBack;
    }

    public interface CallBack {
        void before();

        void after();
    }
}
